<?php

namespace app\libs;

use think\Exception;

/**
 * DES 加密&解密
 */
class Des
{

    // output 的类型
    const OUTPUT_NULL = '';
    const OUTPUT_BASE64 = 'base64';
    const OUTPUT_HEX = 'hex';

    /**
     * 加解密方法，可通过openssl_get_cipher_methods()获得
     */
    protected $method;

    // 加密密钥
    private $key = '';

    // 加解密的向量
    private $iv = '';

    /**
     * @var string $output 输出格式 无、base64、hex
     */
    protected $output;

    protected $options;

    public function __construct($key = 'midou01234567890', $method = 'AES-128-ECB', $output = '', $iv = '', $options = 0)
    {
        //dump(openssl_get_cipher_methods());
        // 加密码方式： AES    模式：ECB    KEY：midou01234567890   偏移： 128     padding: PKCS7
        $this->key = $key;
        $this->method = $method;
        $this->iv = $iv;
        $this->output = $output;
        $this->options = $options;
        //$this->options = OPENSSL_RAW_DATA; // 需要用base64_encode处理，不然是乱码
    }

    /**
     * 加密
     */
    public function encrypt($data)
    {
        $sign = openssl_encrypt($data, $this->method, $this->key, $this->options, $this->iv);

//        if ($this->output == self::OUTPUT_BASE64) {
//            $sign = base64_encode($sign);
//        } else if ($this->output == self::OUTPUT_HEX) {
//            $sign = bin2hex($sign);
//        }

        return $sign;
    }

    /**
     * 解密
     */
    public function decrypt($data)
    {
//        if ($this->output == self::OUTPUT_BASE64) {
//            $encrypted = base64_decode($data);
//        } else if ($this->output == self::OUTPUT_HEX) {
//            $encrypted = hex2bin($data);
//        }

        $sign = @openssl_decrypt($data, $this->method, $this->key, $this->options, $this->iv);

        return $sign;
    }

    /**
     * 填充
     *
     * @param $str
     * @param $blocksize
     * @return string
     */
    private function pkcsPadding($str, $blocksize)
    {
        $pad = $blocksize - (strlen($str) % $blocksize);
        return $str . str_repeat(chr($pad), $pad);
    }

    /**
     * 去填充
     *
     * @param $str
     * @return string
     */
    private function unPkcsPadding($str)
    {
        $pad = ord($str[strlen($str) - 1]);
        if ($pad > strlen($str)) {
            return false;
        }
        return substr($str, 0, -1 * $pad);
    }
}
